$(function() {
	$("#searchType").click(function() {
		var keyword = $("#keyword").val().replace(/(^\s*)|(\s*$)/g, "");
		dataPage(1, keyword);
		// if(keyword != "" && keyword.length != 0) {
		// 	dataPage(1, keyword);
		// }
	});
	//搜索输入框回车事件
	$("#keyword").keydown(function(e) {
		if(e.keyCode == 13) {
			$('#searchType').click();
		}
	});

	//点击添加选项
	$("#itemAddBtn").click(function() {
		
		$("#showValue").val("");
		$("#value").val("");
		for (var i = 0; i < $("#type option").length; i++) {
			if ($("#type").get(0).options[i].value == -1) {
				$("#type").get(0).options[i].selected = true;
				break;
			}
		}
		$("#showMessage").css("display","none");
		$("#valueMessage").css("display","none");
		$("#typeMessage").css("display","none");


		$("#itemId").val("");
		$("#title").html("添加选项");
		$("#itemAdd").modal('show');
	});

	$("#cancleBtn").click(function() {
		$("#itemAdd").modal('hide');
		dataPage(1, "");
	});

	$('#total').change(function() {
		var total = $("#total  option:selected").text();
		// console.info(item);
		dataPage(1, "");
	});

	var dataPage = function(cpage, keyword) {
		var total = $("#total option:selected").text();
		$.ajax({
			url: '/api/item?',
			type: 'get',
			data: {'total':total,'index':cpage,'keyword':keyword, '_t':new Date().getTime()},
			success: function(data) {
				// console.info(data);
				// console.info(data.count);
				// $("#showCount").html("共"+ data.count + "条记录");
				var udata = {};
				if(data == 'noPrivilege'){
					udata = {count:0,data:[]};
				} else {
					udata = data;
				}
				var page;
				if (udata.count < total) {
					page = 1;
				} else {
					page = Math.ceil(udata.count / total);
				}

				var options = {
					currentPage: cpage,
					totalPages: page,
					alignment: 'right',
					count:data.count,
					selectorId: 'pageSeletct',
					onPageChanged: function(e, oldPage, newPage) {
						dataPage(newPage, keyword);
					}
				};

				$('#paginator').bootstrapPaginator(options);
				$("#pageSeletct").change(function() {
					var page = $("#pageSeletct option:selected").val();
					$('#paginator').bootstrapPaginator("show",page);
				});
				showList(udata.data);

			},
			error: function(result) {
				alert('error');
			}

		});
	};
	dataPage(1, "");

	$("#saveBtn").click(function() {
		var sendData = buildModel();
		
		// console.info("sendData:",sendData);
		
		if(sendData.showValue == "") {
			$("#showMsg").html("请填写显示值");
			$("#showMessage").css("display","block");
			return;
		}
		if(sendData.value == ""){
			$("#valueMsg").html("请填写选项值");
			$("#showMessage").css("display","none");
			$("#valueMessage").css("display","block");
			return;
		}
		if(sendData.type == "") {
			$("#typeMessage").html("请选择选项类型");
			$("#valueMessage").css("display","none");
			$("#typeMessage").css("display","block");
			return;
		}
		//判断是新增模式还是编辑模式
		if(sendData.id == ""){
			sendData.urlType = "post";
		}else{
			sendData.urlType = "put";
		}
		$.ajax({
			url: '/api/item/checkItem?',
			type: 'get',
			data: {'sendData':JSON.stringify(sendData), '_t':new Date().getTime()},
			// data: sendData,
			success: function(result) {
				if(result == "showValue") {
					$("#showMsg").html("显示值重复");
					$("#showMessage").css("display","block");
					return;
				}else if(result == "value") {
					$("#valueMsg").html("选项值重复");
					$("#valueMessage").css("display","block");
					return;
				}else{
					saveItem(sendData);
				}
			}
		});

		// saveItem(sendData);


	});
	var saveItem = function(sendData) {
		var cpage = $("#pageSeletct option:selected").val();
		$.ajax({
			url: '/api/item',
			type: sendData.urlType,
			data: sendData,
			success: function(result) {
				// console.info(result);
				//bootbox.alert(result);
				if(result == 'noPrivilege'){
					bootbox.alert('您没有权限,操作失败！');
					return;
				}
				$("#itemAdd").modal('hide');
				// bootbox.alert("选项信息添加成功！");
				
				if(sendData.urlType == "post") {
					bootbox.alert("选项信息添加成功！");
					cpage = 1;

				}else if(sendData.urlType == "put") {
					bootbox.alert("选项信息修改成功！");
				}
				dataPage(cpage, "");
			},
			error: function(result) {
				if(sendData.urlType == "post") {
					bootbox.alert("选项信息添加失败！");
					dataPage(1, "");
				}else{
					bootbox.alert("选项信息更新失败！");
					dataPage(cpage, "");
				}
				$("#itemAdd").modal('hide');
				
			}
		});
	};

	var buildModel = function() {
		var itemId = $("#itemId").val();
		var showValue = $("#showValue").val();
		var value = $("#value").val();
		var type = $("#type option:selected").val() == -1 ? "" : $("#type option:selected").text();

		var model = {};
		
		model.showValue = showValue;
		model.value = value;
		model.type = type;
		model.id = itemId;
		
		
		return model;
	};

	//初始化页面
	// var init = function() {
	// 	$("#itemId").val("");
	// 	$("#showValue").val("");
	// 	$("#value").val("");
	// 	for (var i = 0; i < $("#type option").length; i++) {
	// 		if ($("#type").get(0).options[i].value == -1) {
	// 			$("#type").get(0).options[i].selected = true;
	// 			break;
	// 		}
	// 	}
	// 	$("#showMessage").css("display","none");
	// 	$("#valueMessage").css("display","none");
	// 	$("#typeMessage").css("display","none");


	// 	$.ajax({
	// 		url: '/api/item/selAll',
	// 		type: 'get',
	// 		success: function(data) {
	// 			// console.info(data);
	// 			showList(data);

	// 		}
	// 	});
	// };

    // init();
    var showList = function(data) {
    	$("#itemId").val("");
    	$("#showValue").val("");
    	$("#value").val("");
    	for (var i = 0; i < $("#type option").length; i++) {
    		if ($("#type").get(0).options[i].value == -1) {
    			$("#type").get(0).options[i].selected = true;
    			break;
    		}
    	}
    	$("#showMessage").css("display","none");
    	$("#valueMessage").css("display","none");
    	$("#typeMessage").css("display","none");
    	$("#itemBody").html("");
    	if(data == null || data.length == 0) {
    		$('#tip').html("<div class='alert alert-warning' style='margin-top:-20px;'>未能搜索到相关选项信息</div>");
    	}else{
    		$('#tip').html("");
    	}

    	$.each(data, function(i, item) {
    		var templateData = {
    			itemId: item.id,
    			showValue: item.showValue,
    			value: item.value,
    			type: item.type
    		};

    		var template = "<tr><td class=center><span id=showVal>{{showValue}}</span><input type=hidden id=itemId value={{itemId}}> </td>" + 
    		               "<td class=center id=itemType>{{type}}</td>" + 
    		               "<td class=center id=itemVal>{{value}}</td>" + 
    		               "<td class=center><i id=editIcon style='cursor:pointer;' class='icon-pencil bigger-150'></i>&nbsp;&nbsp;&nbsp;<i id='deleteIcon' style='cursor:pointer;' class='icon-trash  bigger-150'></i></td></tr>";

    		var $html = $(Mustache.to_html(template, templateData));
    		$("#itemBody").append($html);

    		//定义删除按钮删除事件
    		$html.find('#deleteIcon').click({
    			html: $html
    		}, function(e) {
    			var $html = $(e.data.html);
    			var itemId = $html.find("#itemId").val();
    			bootbox.confirm("确定删除该选项信息吗？",function(result) {
    				if(!result) {
    					return;
    				}else{
    					$.ajax({
    						url: '/api/item?id=' + itemId,
    						type:'delete',
    						success: function(result) {
    							if(result == 'noPrivilege'){
    								bootbox.alert('您没有权限,操作失败！');
    								return;
    							}
    							bootbox.alert("删除选项信息成功！", function() {
    								dataPage(1, "");
    							});
    							
    						},
    						error: function(result) {
    							bootbox.alert("删除选项信息失败！", function() {
    								dataPage(1, "");
    							});
    							
    						}
    					});
    				}
    			});
    		});

    		//定义编辑按钮编辑事件
    		$html.find('#editIcon').click({
    			html: $html
    		}, function(e) {

    			var $html = $(e.data.html);
    			var itemId = $html.find('#itemId').val();
    			var showVal = $html.find("#showVal").html();
    			var itemVal = $html.find("#itemVal").html();
    			var itemType = $html.find("#itemType").html();

    			
    			$("#itemId").val(itemId);
    			$("#showValue").val(showVal);
    			$("#value").val(itemVal); 
    			for(var i = 0; i < $("#type option").length; i++) {
    				if($("#type").get(0).options[i].text == itemType) {
    					$("#type").get(0).options[i].selected = true;
    				}
    			}
    			
    			$("#title").html("编辑选项");
    			
    			$("#itemAdd").modal('show');

    		});

    	});
    }

});